#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/types.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>

void do_put(int newfd,char* cmd)
{
	int filefd;
	int ret;
	int filesize = 0;
	char buf[BUFSIZ];
	char* filename;
	
	/*接收从客户端返回的结果*/
	read(newfd,buf,3);//YES或NO
	printf("客户端响应：%s\n",buf);
	if(strncmp(buf,"NO",2) == 0)
	{
		printf("文件不存在，客户端上传终止。\n");
		return;
	}
	else if(strncmp(buf,"YES",3) == 0)
		printf("文件存在，客户端开始上传……\n");
	else
	{
		printf("客户端响应出错。\n");
		return;
	}
	
	/*下载文件*/
	//打开复制文件
	strtok(cmd," ");
	filename = strtok(NULL," ");
	filename[strlen(filename)-1] = '\0';//把末尾的'\n'去掉
	filefd = open(filename,O_WRONLY|O_CREAT|O_TRUNC,0777);
	if(filefd == -1)
	{
		perror("open");
		exit(1);
	}
	
	//复制
	while((ret = read(newfd,buf,BUFSIZ)) == BUFSIZ)
	{
		write(filefd,buf,BUFSIZ);
		bzero(buf, BUFSIZ);
		filesize = filesize + BUFSIZ;
		usleep(100000);//延时100ms
	}
	if(ret > 0)//如果最后一块有残留
	{
		write(filefd,buf,ret);
		filesize = filesize + ret;
	}
	printf("filesize:%d\n",filesize);
	
	//关闭复制文件
	close(filefd);

	/*下载完成*/
	printf("文件下载完毕。\n");
	
	/*挂电话*/
	close(newfd);
}

